import { login, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import global from "@/utils/common";
import router, { resetRouter } from "@/router";

const state = {
  token: getToken(),
  currentUserId: "",
  name: "",
  icon: "",
  avatar: "",
  introduction: "",
  firstLoginStatus: -1,
  roles: [],
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_CURRENTUSERID: (state, currentUserId) => {
    state.currentUserId = currentUserId;
  },
  SET_FILEDOMAIN: (state, fileDomain) => {
    state.fileDomain = fileDomain;
  },
  SET_FILEBUCKET: (state, fileBucket) => {
    state.fileBucket = fileBucket;
  },
  SET_HEADIMG: (state, headImg) => {
    state.headImg = headImg;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_MENU_OPERATE: (state, operateMap) => {
    state.addoperateMap = operateMap;
    state.operateMap = operateMap;
  },
  SET_FIRST_LOGIN_STATUS: (state, firstLoginStatus) => {
    state.firstLoginStatus = firstLoginStatus
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        appKey: window.EnvConfig.VUE_APP_KEY,
      })
        .then((response) => {
          const { data } = response;

          commit("SET_FIRST_LOGIN_STATUS", data.firstLoginStatus)

          commit("SET_TOKEN", data.token);
          setToken(data.token);
          global.token = data.token;

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          response.data["roles"] = ["admin"]; // 不使用框架中提供的前端权限控制,用户权限由后端控制
          const { data } = response;

          if (!data) {
            reject("Verification failed, please Login again.");
          }

          const {
            currentUserId,
            roles,
            name,
            avatar,
            introduction,
            fileDomain,
            fileBucket,
            headImg,
          } = data;

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject("getInfo: roles must be a non-null array!");
          }
          commit("SET_CURRENTUSERID", currentUserId);
          commit("SET_ROLES", roles);
          commit("SET_NAME", name);
          commit("SET_FILEDOMAIN", fileDomain);
          commit("SET_FILEBUCKET", fileBucket);
          commit("SET_HEADIMG", headImg);
          commit("SET_AVATAR", avatar);
          commit("SET_INTRODUCTION", introduction);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      removeToken();
      commit("SET_TOKEN", "");
      commit("SET_CURRENTUSERID", "");
      commit("SET_MENU_OPERATE", []);
      commit("SET_NAME", "");
      commit("SET_FILEDOMAIN", "");
      commit("SET_FILEBUCKET", "");
      commit("SET_HEADIMG", "");
      commit("SET_ROLES", []);
      commit("SET_AVATAR", "");
      commit("SET_INTRODUCTION", "");

      resetRouter();

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch("tagsView/delAllViews", null, { root: true });

      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_MENU_OPERATE", []);
      commit("SET_NAME", "");
      commit("SET_FILEDOMAIN", "");
      commit("SET_FILEBUCKET", "");
      commit("SET_HEADIMG", "");
      commit("SET_AVATAR", "");
      commit("SET_INTRODUCTION", "");
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + "-token";

    commit("SET_TOKEN", token);
    setToken(token);

    const { roles } = await dispatch("getInfo");

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch("permission/generateRoutes", roles, {
      root: true,
    });
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    dispatch("tagsView/delAllViews", null, { root: true });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
